package com.ht.modules.system.config;

import com.ht.modules.system.service.ISysPermissionService;
import com.ht.modules.system.service.ISysUserService;
import com.ht.entity.LoginUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.jeecgframework.core.util.ApplicationContextUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * 权限拦截器
 *
 * @author gaozhihua
 */
@Component
@Slf4j
public class RoleInterceptor implements HandlerInterceptor {
    @Override
    @ExceptionHandler(AuthenticationException.class)
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ISysPermissionService sysPermissionService = ApplicationContextUtil.getContext()
                .getBean(ISysPermissionService.class);
        ISysUserService sysUserService = ApplicationContextUtil.getContext().getBean(ISysUserService.class);
        String url = request.getServletPath();
        if (url != null) {
            url = url.replace("//", "/");
        }
        List<String> allRole = sysPermissionService.getAllRoleByUrl(url);
        // 获取所有的url和url权限 当权限匹配时可以访问
        String username = sysUser.getUsername();
        // 根据用户账号获取角色
        List<String> roleList = sysUserService.getRole(username);
        for (String roleStr : allRole) {
            if (roleList.contains(roleStr)) {
                return true;
            }
        }
        if (allRole.isEmpty()) {
            return true;
        } else {
            log.info("用户{}对菜单{}权限不足", username, url);
            throw new AuthenticationException("权限不足，请联系管理员授权");
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o,ModelAndView modelAndView) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception ex) {
    }
}
